#include "netWork.h"
#include "../common/common.h"

Network::Network()
{
    //init 
    socketFd = -1;
    port = 4399;

    memset(buf_send,0,sizeof(buf_send));
    memset(buf_recv,0,sizeof(buf_recv));
}

Network::~Network()
{

}


int Network::creat_socket_fd()
{
    socketFd = socket(AF_INET,SOCK_DGRAM,0); //创建udp套接字
    if(socketFd == -1)
    {
        goto error;
    }

    

error:
    return socketFd;
}


int Network::bind_socket_point()
{
    int status = -1;
    memset(&seraddr, 0, sizeof(seraddr));
    seraddr.sin_family = AF_INET;
    seraddr.sin_port = htons(port);
    seraddr.sin_addr.s_addr = inet_addr("0.0.0.0");
    status = bind(socketFd, (struct sockaddr *)&seraddr, sizeof(seraddr));
    if(-1 == status)
    {
        return -1;
    }
    return status;
}


int Network::send_socket_data(int length)
{
    socklen_t addrlen = sizeof(seraddr);

    int ret = sendto(socketFd, buf_send, length, 0, (struct sockaddr *)&cliaddr, addrlen);
    if(-1 == ret)
    {
        perror("sento");
        return -1;
    }
    return 0;
}

int Network::recv_socket_data()
{
    socklen_t addrlen = sizeof(seraddr);
    //step 3:接受数据
    int ret = recvfrom(socketFd, buf_recv, sizeof(buf_recv), 0, (struct sockaddr *)&cliaddr, &addrlen);
    if(-1 == ret)
    {
        perror("recvfrom");
        return -1;
    }
    printf("recv from %s:%d, content is %s\n", inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port), buf_recv);
}


int Network::check_client_netType()
{
    //
    return 0;
}